package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.MemberDao;
import com.huike.pmps.dao.ProvincesDao;
import com.huike.pmps.dao.RegionDao;
import com.huike.pmps.dao.RoleDao;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.dto.member.MemberRoleDTO;
import com.huike.pmps.model.entity.Member;
import com.huike.pmps.model.entity.Role;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.MemberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    MemberDao memberDao;
    @Autowired
    RoleDao roleDao;
    @Autowired
    RegionDao regionDao;
    @Autowired
    ProvincesDao provincesDao;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 添加用户
     *
     * @param member
     * @return
     */
    @Override
    public Result insertOne(Member member) {
        Member byMemberName = memberDao.findByMemberName(member.getMemberName());
        if (byMemberName != null) return Result.failure("用户名重复,添加失败");
        member.setPassword(bCryptPasswordEncoder.encode(member.getPassword()));
        member.setCreateTime(new Date());
        memberDao.insert(member);
        return Result.success();
    }

    /**
     * 更新用户
     *
     * @param member
     * @return
     */
    @Override
    public Result updateById(Member member) {
        if (StringUtils.isNotBlank(member.getPassword())) {
            member.setPassword(bCryptPasswordEncoder.encode(member.getPassword()));
        }
        memberDao.updateById(member);
        return Result.success();
    }

    /**
     * 获取单个用户
     *
     * @param memberId
     * @return
     */
    @Override
    public Result selectOneByMemberId(int memberId) {
        Member member = memberDao.findById(memberId);
        if (member != null) {
            List<Integer> rolesId = new ArrayList<>();
            for (Role role : member.getRoles()) {
                rolesId.add(role.getId());
            }
            member.setRolesIds(rolesId);
            return Result.success(member);
        } else
            return Result.failure("不存在此用户");

    }


    /**
     * 按搜索条件分页查询用户
     *
     * @param pageInfo
     * @param memberName
     * @param name
     * @param sex
     * @param state
     * @return
     */
    @Override
    public Result selectByCondition(PageInfo pageInfo, String memberName, String name, Short sex, Short state) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(memberName))
            queryWrapper.like("member_name", memberName);
        if (StringUtils.isNotBlank(name))
            queryWrapper.like("name", name);
        if (sex != null)
            queryWrapper.eq("sex", sex);
        if (state != null)
            queryWrapper.eq("state", state);


        queryWrapper.orderByDesc("id");

        Page<Member> page = new Page<Member>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<Member> memberPage = memberDao.selectPage(page, queryWrapper);

        if (memberPage.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(memberPage.getCurrent()).pageSize(memberPage.getSize())
                    .total(memberPage.getTotal()).rows(memberPage.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }


    }

    /**
     * 用户启用或禁用
     *
     * @param memberId
     * @param state
     * @return
     */
    @Override
    public Result updateMemberStateByMemberId(Integer memberId, Short state) {
        Member member = Member.builder().id(memberId).state(state).build();
        memberDao.updateById(member);
        return Result.success();
    }

    /**
     * 用户密码更新
     *
     * @param memberId
     * @param newPassword
     * @return
     */
    @Override
    public Result updateMemberPasswordByMemberId(Integer memberId, String newPassword) {
        Member member = Member.builder().id(memberId).password(bCryptPasswordEncoder.encode(newPassword)).build();
        memberDao.updateById(member);
        return Result.success("密码更新成功");
    }

    /**
     * 删除用户
     *
     * @param memberId
     * @return
     */
    @Override
    public Result deleteByMemberId(Integer memberId) {
        if (memberId == 1)
            return Result.failure("系统超级用户，不可删除");
        //删除用户
        memberDao.deleteById(memberId);
        //删除用户角色关系
        memberDao.deleteMemberAndRoleRelationByMemberId(memberId);
        return Result.success("删除用户成功");
    }

    /**
     * 更新用户角色关系
     *
     * @param memberId
     * @param roleIds
     * @return
     */
    @Override
    public Result insertMemberAndRoleRelation(Integer memberId, String roleIds) {
        List<MemberRoleDTO> memberRoleDTOList = new ArrayList<>();
        for (String roleId : roleIds.split(",")) {
            MemberRoleDTO memberRoleDTO = new MemberRoleDTO(memberId, Integer.valueOf(roleId));
            memberRoleDTOList.add(memberRoleDTO);
        }
        //根据用户memberId，删除原有(用户角色关系表)中的数据
        memberDao.deleteMemberAndRoleRelationByMemberId(memberId);
        //添加新的用户角色关系数据
        memberDao.insertMemberAndRoleRelation(memberRoleDTOList);
        return Result.success();
    }

    @Override
    public Result selectCourseCharge(Member member) {
        Integer regionId = member.getRegionId();
        //获取该战区下所有课程编导
        List<Member> members = null;
        if (member.getRolesIds().contains(1)) {//超级管理员角色
            members = memberDao.findAllCourseCharge();
        } else {
            members = memberDao.finByRegionId(regionId);
        }
        members.forEach(m -> {
            m.setRolesIds(null);
            m.setRoles(null);
        });
        return Result.success(members);
    }


}
